package cn.steel.controller.supplier;

import cn.hutool.core.bean.BeanUtil;
import cn.steel.base.ResponseData;
import cn.steel.domain.dto.ProductDto;
import cn.steel.domain.entity.Product;
import cn.steel.domain.vo.ProductVo;
import cn.steel.domain.entity.User;
import cn.steel.mapper.SupplierInfoMapper;
import cn.steel.mapper.UserMapper;
import cn.steel.service.ProductService;
import cn.steel.utils.ExcelUtils;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.Arrays;
import java.util.List;


@Slf4j
@Controller
@RequestMapping("/supplier/product")
@Api(tags = "供应商商品管理接口")
@PreAuthorize("hasAuthority('SUPPLIER')")
@RequiredArgsConstructor
public class SupplierProductController {

    private final ProductService productService;
    private final SupplierInfoMapper supplierInfoMapper;
    private final UserMapper userMapper;

    @ApiOperation("显示供应商商品列表页面")
    @GetMapping
    public String productList(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String search,
            @RequestParam(required = false) Long categoryId,
            @RequestParam(required = false) Integer status,
            @SessionAttribute(value = "user", required = false) User user,  // 从 Session 中获取当前用户信息
            Model model) {
        if (user == null || user.getId() == null) {
            // 如果用户未登录或没有供应商 ID，可以根据需求重定向或返回错误页面
            return "redirect:/login";
        }

        log.info("显示供应商商品列表页面: page={}, size={}, search={}, categoryId={}, status={}, supplierId={}",
                page, size, search, categoryId, status, user.getId());

        Long supplierId = user.getId();  // 从登录用户获取供应商 ID
        PageHelper.startPage(page, size);
        Page<ProductVo> pageResult = productService.getProductsPaginated(search, null, categoryId, null, supplierId, status);
        model.addAttribute("products", pageResult.getResult());
        model.addAttribute("totalPages", pageResult.getPages());
        model.addAttribute("totalItems", pageResult.getTotal());
        model.addAttribute("currentPage", pageResult.getPageNum());
        model.addAttribute("pageSize", size);
        model.addAttribute("search", search);
        model.addAttribute("categoryId", categoryId);
        model.addAttribute("status", status);
        model.addAttribute("categories", productService.getCategories());
        return "supplier/product_supplier_list";
    }

    @ApiOperation("预览商品详情")
    @GetMapping("/preview")
    public String previewProduct(@RequestParam Long id, @SessionAttribute(value = "user", required = false) User user, Model model) {
        if (user == null || !"SUPPLIER".equals(user.getRole())) {
            return "redirect:/login";
        }
        log.info("预览商品详情: productId={}", id);
        Product product = productService.getProductById(id);
        if (product == null || !product.getSupplierId().equals(user.getId())) {
            model.addAttribute("errorMessage", "商品不存在或无权限预览");
            return "error";
        }
        ProductVo productVo = BeanUtil.toBean(product, ProductVo.class);
        productVo.setCategoryName(product.getCategoryId() != null ? productService.findCategoryById(product.getCategoryId()) : null);
        model.addAttribute("product", productVo);
        return "buyer/product_details"; // 复用买家详情页面
    }

    @ApiOperation("跳转到商品添加页面")
    @GetMapping("/add")
    public String toAddPage(Model model) {
        model.addAttribute("product", new ProductDto());
        model.addAttribute("categories", productService.getCategories());
        return "supplier/product_form";
    }

    @ApiOperation("添加商品")
    @PostMapping("/add")
    public String addProduct(
            @SessionAttribute("user") User user,
            @ModelAttribute ProductDto productDto,
            @RequestParam("materialReportFile") MultipartFile materialReportFile,
            @RequestParam("imageFile") MultipartFile imageFile,
            RedirectAttributes redirectAttributes) {
        Product product = BeanUtil.toBean(productDto, Product.class);
        product.setSupplierId(user.getId());
        product.setStatus(0);
        try {
            productService.addProduct(product, materialReportFile, imageFile);
            redirectAttributes.addFlashAttribute("successMessage", "商品添加成功");
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("errorMessage", "商品添加失败：" + e.getMessage());
        }
        return "redirect:/supplier/product";
    }

    @ApiOperation("跳转到商品编辑页面")
    @GetMapping("/edit")
    public String toEditPage(@RequestParam Long id, Model model) {
        Product product = productService.getProductById(id);
        model.addAttribute("product", product);
        model.addAttribute("categories", productService.getCategories());
        return "supplier/product_form";
    }
    @ApiOperation("编辑商品")
    @PutMapping("/update")
    public String updateProduct(
            @SessionAttribute("user") User user,
            @ModelAttribute ProductDto productDto,
            @RequestParam("materialReportFile") MultipartFile materialReportFile,
            @RequestParam("imageFile") MultipartFile imageFile,
            RedirectAttributes redirectAttributes) {
        Product product = BeanUtil.toBean(productDto, Product.class);
        product.setSupplierId(user.getId());
//        product.setStatus(0);
        try {
            Product existing = productService.getProductById(product.getId());
            if (existing == null || !existing.getSupplierId().equals(user.getId())) {
                throw new IllegalArgumentException("商品不存在或无权限编辑");
            }
            productService.updateProduct(product, materialReportFile, imageFile);
            redirectAttributes.addFlashAttribute("successMessage", "商品修改成功");
        } catch (Exception e) {
            log.error("编辑商品失败: id={}, error={}", product.getId(), e.getMessage());
            redirectAttributes.addFlashAttribute("errorMessage", "商品修改失败：" + e.getMessage());
        }
        return "redirect:/supplier/product?success=true";
    }

    @ApiOperation("删除商品")
    @DeleteMapping("/delete")
    public String deleteProduct(@RequestParam Long id,
                                @SessionAttribute(value = "user", required = false) User user,
                                RedirectAttributes redirectAttributes) {
        try {
            Product product = productService.getProductById(id);
            if (product == null || !product.getSupplierId().equals(user.getId())) {
                throw new IllegalArgumentException("商品不存在或无权限删除");
            }
            productService.deleteProduct(id);
            redirectAttributes.addFlashAttribute("successMessage", "商品删除成功");
        } catch (Exception e) {
            log.error("删除商品失败: id={}, error={}", id, e.getMessage());
            redirectAttributes.addFlashAttribute("errorMessage", "商品删除失败：" + e.getMessage());
        }
        return "redirect:/supplier/product";
    }

    @ApiOperation("批量导入商品")
    @PostMapping("/batch-import")
    public String batchImportProducts(
            @SessionAttribute("user") User user,
            @RequestParam("excelFile") MultipartFile excelFile,
            RedirectAttributes redirectAttributes) {
        try {
            List<Product> products = ExcelUtils.parseExcel(excelFile);
            productService.batchImportProducts(products, user.getId());
            redirectAttributes.addFlashAttribute("successMessage", "批量导入商品成功");
        } catch (Exception e) {
            log.error("批量导入商品失败: {}", e.getMessage());
            redirectAttributes.addFlashAttribute("errorMessage", "批量导入商品失败：" + e.getMessage());
        }
        return "redirect:/supplier/product";
    }

    @ApiOperation("导出商品")
    @GetMapping("/export")
    public ResponseEntity<byte[]> exportProducts(
            @RequestParam(required = false) String search,
            @RequestParam(required = false) Long categoryId,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) List<String> fields,
            @SessionAttribute("user") User user) {
        try {
            List<Product> products = productService.getProductsForExport(search, categoryId, status, user.getId());
            if (fields == null || fields.isEmpty()) {
                fields = Arrays.asList("商品名称", "分类ID", "规格", "材质", "库存", "价格", "发货地址", "发货区域");
            }
            byte[] excelData = ExcelUtils.exportExcel(products, fields);
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", "products.xlsx");
            return ResponseEntity.ok().headers(headers).body(excelData);
        } catch (Exception e) {
            log.error("导出商品失败: {}", e.getMessage());
            throw new RuntimeException("导出商品失败：" + e.getMessage());
        }
    }
}
